package hbase.client;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HBaseClient {

    private static HBaseClient client = null;
    Configuration conf = null;
    Connection conn = null;

    public static HBaseClient create() throws IOException {
        if (client == null) {
            client = new HBaseClient();
        }
        return  client;
    }

    public HBaseClient() throws IOException {
        init();
    }

    public void init() throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "192.168.8.103,192.168.8.104");
        conf.set("hbase.zookeeper.property.clientPort", "2181");

        conn = ConnectionFactory.createConnection();
    }

    public void createTable(String tableName, String[] families) throws IOException {
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        final HTableDescriptor table = new HTableDescriptor(TableName.valueOf(tableName));
        for (int i = 0; i < families.length; i++) {
            table.addFamily(new HColumnDescriptor(families[i]));
        }
        admin.createTable(table);
        System.out.println(tableName + "表创建成功");
    }

    public void putData(String tableName, String rowKey, String familyName, String columnName, String columnValue) throws IOException {
        //需要获取一个table对象
        final Table worker = conn.getTable(TableName.valueOf(tableName));

        //准备put对象
        final Put put = new Put(Bytes.toBytes(rowKey));//指定rowkey

        put.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName), Bytes.toBytes(columnValue));
        //插入数据，参数类型是put
        worker.put(put);
        //准备list<puts>,可以执行批量插入
        //关闭table对象
        worker.close();
        System.out.println("插入数据到" + tableName + "表成功！！");
    }

    public void deleteData(String tableName, String rowKey) throws IOException {
        //需要获取一个table对象
        final Table table = conn.getTable(TableName.valueOf(tableName));

        //准备delete对象
        final Delete delete = new Delete(Bytes.toBytes(rowKey));
        //执行删除
        table.delete(delete);
        //关闭table对象
        table.close();
        System.out.println("删除数据成功！！");
    }

    public void realse() {
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
